// app/extend/helper.js

const xlsx = require('node-xlsx');
const fs = require('fs');
const path = require('path');
const fileDir = require('../utils/config').fileDir;

module.exports = {
  sendOk(data) {
    return {
      code: 0,
      data,
      msg: '请求成功',
    };
  },
  sendErr(msg) {
    return {
      code: 400,
      msg,
    };
  },

  /**
   * 保存excel到本地
   * @param table 数据
   * @param name 文件名
   * @param colWidth 列宽 [20,12,11]
   * @param fileName 保存文件夹位置
   * @return {Promise<void> | Promise<any>}
   */
  saveExcel(table, name, colWidth, dictionary) {
    const widthList = colWidth.map(width => ({ wch: width }));
    const options = { '!cols': widthList };
    const buffer = xlsx.build([{ name: 'sheet1', data: table }], options); // Returns a buffer

    const fileName = name + '-' + new Date().getTime() + '.xlsx';
    fs.writeFileSync(fileDir +'/'+ fileName, buffer, 'binary');
    return 'http://47.114.61.255/downFile/' + fileName
  },
};